<?php

declare(strict_types=1);

namespace App\Controller\MchApi;

use App\Exception\XZXValidationException;
use App\Middleware\MchApi\MchJWTAuthMiddleware;
use App\Service\MchSysAdminService;
use App\Utils\CustomUtils;
use App\Utils\DateUtils;
use Hyperf\Di\Annotation\Inject;
use Hyperf\HttpServer\Annotation\Controller;
use Hyperf\HttpServer\Annotation\Middleware;
use Hyperf\HttpServer\Annotation\PostMapping;
use Hyperf\HttpServer\Contract\RequestInterface;
use Hyperf\Logger\LoggerFactory;
use Hyperf\Validation\Contract\ValidatorFactoryInterface;
use App\Constants\XZXResponseCode;
use Hyperf\Contract\TranslatorInterface;

/**
 * Class MchSysAdminController
 * @package App\Controller
 *
 * @Controller(prefix="/mch/api/mchSysAdmin")
 */
class MchSysAdminController extends MchBaseController
{
    /**
     * @Inject
     * @var TranslatorInterface
     */
    private $translator;

    /**
     * @Inject()
     * @var ValidatorFactoryInterface
     */
    protected $validationFactory;

    /**
     * @Inject()
     * @var MchSysAdminService
     */
    protected $MchSysAdminService;

    /**
     * @var \Psr\Log\LoggerInterface
     */
    protected $logger;

    public function __construct(LoggerFactory $loggerFactory)
    {
        // 第一个参数对应日志的 name, 第二个参数对应 config/autoload/logger.php 内的 key
        $this->logger = $loggerFactory->get('log', 'default');
    }

    private function setLocale()
    {
        if($this->request->header('locale') == 'en')
        {
            $this->translator->setLocale('en');
        }
    }    

    /**
     * 查看
     * @PostMapping(path = "get")
     * @Middleware(MchJWTAuthMiddleware::class)
     */
    public function get(RequestInterface $request)
    {
        $this->setlocale();
        $validator = $this->validationFactory->make(
            $request->all(),
            [
                'id' => 'required|uuid',
            ]
        );

        if ($validator->fails()){
            // Handle exception
            $errorMessage = $validator->errors()->first();  
            throw new XZXValidationException($errorMessage);
        }

        $param = $request->all();
        $ext = $this->request->getAttribute("ext");
        isset($ext['uid']) && $param['uid'] = trim($ext['uid']); 
        $param['mchId'] = $ext['mchId']; 
        $param['source'] = 1;
        return $this->MchSysAdminService->get($param);
    }

    /**
     * 编辑
     * @PostMapping(path = "edit")
     * @Middleware(MchJWTAuthMiddleware::class)
     */
    public function edit(RequestInterface $request)
    {
        $this->setlocale();
        $validator = $this->validationFactory->make(
            $request->all(),
            [
                'id'                    => 'required|uuid',
                // 'username'           => 'sometimes|required|between:4,8|alpha_num',
                'password'              => 'sometimes|required|between:5,16|alpha_dash|confirmed',
                'password_confirmation' => 'sometimes|required|between:5,16|alpha_dash',
                'nick'                  => 'sometimes|required',
                'realName'              => 'sometimes|required',
                'mobile'                => 'sometimes|required',
                'email'                 => 'sometimes|required|email',
                'roleId'                => 'sometimes|required|uuid',
                'status'                => 'sometimes|required|integer|max:1|min:0',
                'googleAuthSecret'      => 'sometimes|required|size:16',
                // 'mchId'                 => 'sometimes|required|uuid',                 
            ]
        );

        if ($validator->fails()){
            // Handle exception
            $errorMessage = $validator->errors()->first();  
            throw new XZXValidationException($errorMessage);
        }

        $param = $request->all();
        $ext = $this->request->getAttribute("ext");
        isset($ext['uid']) && $param['uid'] = trim($ext['uid']); 
        $param['mchId'] = $ext['mchId']; 
        // $param['from'] = 'mch';
        $param['source'] = 1;
        return $this->MchSysAdminService->edit($param);
    }

    /**
     * 添加
     * @PostMapping(path = "add")
     * @Middleware(MchJWTAuthMiddleware::class)
     */
    public function add(RequestInterface $request)
    {
        $this->setlocale();
        $validator = $this->validationFactory->make(
            $request->all(),
            [
                'username'              => 'required|between:4,8|alpha_num',
                'password'              => 'required|between:5,16|alpha_dash|confirmed',
                'password_confirmation' => 'required|between:5,16|alpha_dash',
                'nick'                  => 'required',
                'realName'              => 'required',
                'mobile'                => 'required',
                'email'                 => 'required|email',
                'roleId'                => 'required|uuid',
                'status'                => 'required|integer|max:1|min:0',
                // 'googleAuthSecret'   => 'required|size:16',
                'mchId'                 => 'sometimes|required|uuid',
            ]
        );

        if ($validator->fails()){
            // Handle exception
            $errorMessage = $validator->errors()->first();  
            throw new XZXValidationException($errorMessage);
        }

        $param = $request->all();
        // $param['from'] = 'mch';
        $param['source'] = 1;
        $ext = $this->request->getAttribute("ext");        
        $param['mchId'] = $ext['mchId']; //从商户后台上来的会传这个mchId ,如果有，则以这个为准赋值
        return $this->MchSysAdminService->add($param);
    }

    /**
     * 删除
     * @PostMapping(path = "del")
     * @Middleware(MchJWTAuthMiddleware::class)
     */
    public function del(RequestInterface $request)
    {

        // $validator = $this->validationFactory->make(
        //     $request->all(),
        //     [
        //         'id' => 'required',
        //     ],
        // );

        // if ($validator->fails()){
        //     // Handle exception
        //     $errorMessage = $validator->errors()->first();  
        //     throw new XZXValidationException($errorMessage);
        // }

        // $param = $request->all();
        // return $this->MchSysAdminService->del($param);
    }

    /**
     * 查询
     * @PostMapping(path = "list")
     * @Middleware(MchJWTAuthMiddleware::class)
     */
    public function list(RequestInterface $request)
    {
        $this->setlocale();
        $validator = $this->validationFactory->make(
            $request->all(),
            [
                'page'            => 'required|integer|min:1',
                'limit'           => 'required|integer|min:1',
                'search.email'    => 'sometimes|required|email',
                'search.roleId'   => 'sometimes|required|uuid',
                'search.status'   => 'sometimes|required|integer|max:1|min:0',                
                'search.mobile'   => 'sometimes|required',              
                'search.username' => 'sometimes|required|between:4,8|alpha_num',  
                'search.nick'     => 'sometimes|required',   
                'search.realName' => 'sometimes|required',                
            ]
        );        

        if ($validator->fails()){
            // Handle exception
            $errorMessage = $validator->errors()->first();  
            throw new XZXValidationException($errorMessage);
        }
        
        $param = $request->all();
        $ext = $this->request->getAttribute("ext");

        // $ext['mchId'] = '39BE020A-0BCF-F139-C11F-13CF764C2675';
        $param['mchId'] = $ext['mchId']; //06EF629F-5678-F5DD-2F9D-702A5F22BB4A

        if(isset($param['search'])){
            $search = $param['search'];        
            CustomUtils::xzxAddSearch($param, $search, 'email');
            CustomUtils::xzxAddSearch($param, $search, 'mobile');
            CustomUtils::xzxAddSearch($param, $search, 'status');
            CustomUtils::xzxAddSearch($param, $search, 'roleId');
            CustomUtils::xzxAddSearch($param, $search, 'realName');
            CustomUtils::xzxAddSearch($param, $search, 'username');
            CustomUtils::xzxAddSearch($param, $search, 'nick');
            CustomUtils::xzxAddSearch($param, $search, 'createTimeRange');
            if(isset($param["createTimeRange"]))
            {
                try {
                    $param['createTimeRange'][0] = DateUtils::dateToTimeStamp($param['createTimeRange'][0]);
                    $param['createTimeRange'][1] = DateUtils::dateToTimeStamp($param['createTimeRange'][1]);
                } catch (\Throwable $th) {
                    unset($param['createTimeRange']);
                }
            }
    
        }

        
        return $this->MchSysAdminService->list($param);
    }

    /**
     * Login
     * @PostMapping(path = "login")
     */ 
    public function login(RequestInterface $request) {
        $this->setlocale();
        $validator = $this->validationFactory->make(
            $request->all(),
            [
                'username' => 'required|between: 4,30',
                'password' => 'required|between: 5,16|alpha_dash',
                'email'    => 'required|email',
                'code'     => 'required',
            ]
        );

        if ($validator->fails()){
            // Handle exception
            $errorMessage = $validator->errors()->first();  
            throw new XZXValidationException($errorMessage);
        }
        $param = $request->all();
        return $this->MchSysAdminService->login($param);
    }

    /**
     * Login
     * @PostMapping(path = "logout")
     * @Middleware(MchJWTAuthMiddleware::class)
     */
    public function logout(RequestInterface $request) {
        $this->setlocale();
        $param = array();
        $ext = $this->request->getAttribute("ext");
        $param['uid']      =  $ext['uid']; 
        
        CustomUtils::xzxDebug($param);
        
        return $this->MchSysAdminService->logout($param);
    }

    /**
     * 重置google密钥
     * @PostMapping(path = "resetGoogleAuthSecret")
     * @Middleware(MchJWTAuthMiddleware::class)
     */ 
    public function resetGoogleAuthSecret(RequestInterface $request) {
        $this->setlocale();
        // $param['id'] = trim($request->post('id'));
        $validator = $this->validationFactory->make(
            $request->all(),
            [
                'id' => 'required|uuid',
            ]
        );

        if ($validator->fails()){
            // Handle exception
            $errorMessage = $validator->errors()->first();  
            throw new XZXValidationException($errorMessage);
        }

        $param = $request->all();

        return $this->MchSysAdminService->resetGoogleAuthSecret($param);
    }

    /**
     * 忘记管理员密码
     * @PostMapping(path = "forgotPassword")     
     */ 
    public function forgotPassword(RequestInterface $request) {
        $this->setlocale();
        // $param['id'] = trim($request->post('id'));
        $validator = $this->validationFactory->make(
            $request->all(),
            [
                'mchEmail' => 'required|email',
                'email' => 'required|email',
            ]
        );

        if ($validator->fails()){
            // Handle exception
            $errorMessage = $validator->errors()->first();  
            throw new XZXValidationException($errorMessage);
        }

        $param = $request->all();

        return $this->MchSysAdminService->forgotPassword($param);
    }

    /**
     * 重置商户管理员密码
     * @PostMapping(path = "resetPassword")     
     */ 
    public function resetPassword(RequestInterface $request) {
        $this->setlocale();
        // $param['id'] = trim($request->post('id'));
        $validator = $this->validationFactory->make(
            $request->all(),
            [
                'hashCode'              => 'required',
                'password'              => 'required|between:5,16|alpha_dash|confirmed',
                'password_confirmation' => 'required|between:5,16|alpha_dash',       
                'code'                  => 'required'
            ]
        );

        if ($validator->fails()){
            // Handle exception
            $errorMessage = $validator->errors()->first();  
            throw new XZXValidationException($errorMessage);
        }

        $param = $request->all();
        $param['source'] = 1;
        return $this->MchSysAdminService->resetPassword($param);
    }

    /**
     * 修改商户管理员密码
     * @PostMapping(path = "changePassword")   
     * @Middleware(MchJWTAuthMiddleware::class)  
     */
    public function changePassword (RequestInterface $request) {
        $this->setlocale();
        // $param = [];

        // $param['passwordNow'] = trim($request->post('passwordNow'));
        // $param['password']    = trim($request->post('password'));
        // $param['id']          = trim($request->ext['uid']);

        // xeDebug($param);

        $validator = $this->validationFactory->make(
            $request->all(),
            [
                'password'              => 'required|between:5,16|alpha_dash|confirmed',
                'password_confirmation' => 'required|between:5,16|alpha_dash',       
            ]
        );

        if ($validator->fails()){
            // Handle exception
            $errorMessage = $validator->errors()->first();  
            throw new XZXValidationException($errorMessage);
        }

        $param = $request->all();
        $ext = $this->request->getAttribute("ext");
        $param['id']      =  $ext['uid']; 
        $param['source'] = 1;

        return $this->MchSysAdminService->changePassword($param);

        // return xeResponseData($result['code'],$result['message'],$result['data']);

    }

    /**
     * 修改商户管理员google 密钥
     * @PostMapping(path = "resetAppSecret")   
     * @Middleware(MchJWTAuthMiddleware::class)  
     */
    public function resetAppSecret (RequestInterface $request) {
        $this->setlocale();
        // $param = [];

        // $isSuperRole = $request->ext["isSuperRole"];
        $param = $request->all();
        $ext = $this->request->getAttribute("ext");
        // CustomUtils::xzxDebug($ext);
        $isSuperRole = $ext["isSuperRole"];

        // 只有超级管理员允许修改
        if (!$isSuperRole) {
            // throw new \Exception("没有操作权限");
            throw new XZXValidationException(XZXResponseCode::getMessage(XZXResponseCode::NO_PERMISSION_TO_OPERATE));
        }

        $param["mchId"] = $ext['mchId'];

        // xeDebug($param);

        return $this->MchSysAdminService->resetAppSecret($param);

        // return xeResponseData($result['code'],$result['message'],$result['data']);

    }
   
}